import { useState } from 'react'
import { Form, Input, Button, Card, message, Typography, Space } from 'antd'
import { UserOutlined, LockOutlined } from '@ant-design/icons'
import { useNavigate } from 'react-router-dom'
import axios from 'axios'
import { setUserInfo, type UserInfo, getRoleName } from '../../utils/auth'
import SliderCaptchaCanvas from '../../components/SliderCaptchaCanvas'

const { Title, Text } = Typography

// 定义登录接口的请求和响应类型
interface LoginRequest {
  account: string
  password: string
}

interface LoginResponse {
  username: string
  role: number
  userId: number
  token: string
}

function LoginPage() {
  const [loading, setLoading] = useState(false)
  const [captchaVisible, setCaptchaVisible] = useState(false)
  const [form] = Form.useForm()
  const navigate = useNavigate()

  // 使用库自带的“竖向切片对齐”规则：返回相同图片作为背景与切片来源

  // 处理登录提交
  const handleLogin = async (values: LoginRequest) => {
    setLoading(true)
    try {
      console.log('正在尝试登录...', values)
      
      // 检查是否为普通用户，使用模拟登录
      if (values.account === 'user' && values.password === 'a123456') {
        console.log('普通用户模拟登录...')
        
        // 模拟网络延迟
        await new Promise(resolve => setTimeout(resolve, 800))
        
        // 模拟普通用户登录数据
        const mockUserInfo: UserInfo = {
          username: 'user',
          role: 0, // 普通用户
          userId: 12345678,
          token: 'mock_token_for_user_' + Date.now()
        }
        
        setUserInfo(mockUserInfo)
        
        const roleName = getRoleName(mockUserInfo.role)
        message.success(`欢迎回来，${mockUserInfo.username}！您的角色：${roleName} (模拟登录)`)
        
        // 登录成功后显示验证码
        setCaptchaVisible(true)
        
        return
      }
      
      // 管理员用户走真实接口
      const response = await axios.post<LoginResponse>('http://172.27.2.110/login', {
        account: values.account,
        password: values.password
      })

      console.log('登录成功:', response.data)
      
      // 使用工具函数存储用户信息
      const userInfo: UserInfo = {
        username: response.data.username,
        role: response.data.role,
        userId: response.data.userId,
        token: response.data.token
      }
      setUserInfo(userInfo)
      
      const roleName = getRoleName(response.data.role)
      message.success(`欢迎回来，${response.data.username}！您的角色：${roleName}`)
      
      // 登录成功后显示验证码
      setCaptchaVisible(true)
      
    } catch (error: unknown) {
      console.error('登录失败:', error)
      
      // 处理不同类型的错误
      if (axios.isAxiosError(error)) {
        if (error.response) {
          // 服务器返回了错误状态码
          const status = error.response.status
          if (status === 401) {
            message.error('用户名或密码错误，请检查后重试')
          } else if (status === 403) {
            message.error('账户已被禁用，请联系管理员')
          } else if (status >= 500) {
            message.error('服务器内部错误，请稍后重试')
          } else {
            message.error(`登录失败：${error.response.data?.message || '未知错误'}`)
          }
        } else if (error.request) {
          // 网络错误
          message.error('网络连接失败，请检查网络后重试')
        } else {
          // 其他错误
          message.error('登录过程中发生未知错误')
        }
      } else {
        // 非axios错误
        message.error('登录过程中发生未知错误')
      }
    } finally {
      setLoading(false)
    }
  }

  // 处理验证成功
  const handleCaptchaSuccess = () => {
    setCaptchaVisible(false)
    message.success('验证成功！')
    
    // 验证成功后跳转到主页面
    setTimeout(() => {
      navigate('/')
    }, 500)
  }

  // 处理验证取消
  const handleCaptchaCancel = () => {
    setCaptchaVisible(false)
    message.warning('验证已取消，请重新登录')
    
    // 清除用户信息
    localStorage.removeItem('userInfo')
    form.resetFields()
  }

  // 解析来自后端回跳的 Gitee 登录数据（hash 中 base64）
  if (typeof window !== 'undefined') {
    const hash = window.location.hash
    if (hash.startsWith('#data=')) {
      try {
        const b64 = decodeURIComponent(hash.slice(6))
        const json = JSON.parse(atob(b64)) as { accessToken: string; user: any }
        // 统一写入本地登录态
        const userInfo: UserInfo = {
          username: json.user?.name || json.user?.login || 'gitee_user',
          role: 0,
          userId: Number(json.user?.id) || Date.now(),
          token: json.accessToken || ('gitee_' + Date.now())
        }
        setUserInfo(userInfo)
        message.success(`Gitee 登录成功，欢迎 ${userInfo.username}`)
        // 清理 hash，避免重复解析
        const cleanUrl = window.location.pathname + window.location.search
        window.history.replaceState(null, '', cleanUrl)
        // 直接通过滑块校验流程
        setCaptchaVisible(true)
      } catch {}
    }
  }

  // 表单验证规则
  const validationRules = {
    account: [
      { required: true, message: '请输入用户名' },
      { min: 2, message: '用户名至少2个字符' },
      { max: 20, message: '用户名不能超过20个字符' }
    ],
    password: [
      { required: true, message: '请输入密码' },
      { min: 6, message: '密码至少6个字符' },
      { max: 20, message: '密码不能超过20个字符' }
    ]
  }

  return (
    <div style={{
      minHeight: '100vh',
      display: 'flex',
      justifyContent: 'center',
      alignItems: 'center',
      background: 'linear-gradient(135deg, #667eea 0%, #764ba2 100%)',
      padding: '20px'
    }}>
      <Card 
        style={{ 
          width: '100%', 
          maxWidth: 400,
          boxShadow: '0 8px 32px rgba(0,0,0,0.1)',
          borderRadius: '12px'
        }}
        bodyStyle={{ padding: '40px 30px' }}
      >
        <Space direction="vertical" size="large" style={{ width: '100%' }}>
          {/* 标题区域 */}
          <div style={{ textAlign: 'center' }}>
            <Title level={2} style={{ margin: 0, color: '#1890ff' }}>
              数字人系统
            </Title>
            <Text type="secondary" style={{ fontSize: '16px' }}>
              请登录您的账户
            </Text>
          </div>

          {/* 登录表单 */}
          <Form
            form={form}
            name="login"
            onFinish={handleLogin}
            layout="vertical"
            size="large"
            autoComplete="off"
          >
            <Form.Item
              name="account"
              label="用户名"
              rules={validationRules.account}
            >
              <Input
                prefix={<UserOutlined style={{ color: '#bfbfbf' }} />}
                placeholder="请输入用户名"
                autoComplete="username"
              />
            </Form.Item>

            <Form.Item
              name="password"
              label="密码"
              rules={validationRules.password}
            >
              <Input.Password
                prefix={<LockOutlined style={{ color: '#bfbfbf' }} />}
                placeholder="请输入密码"
                autoComplete="current-password"
              />
            </Form.Item>

            <Form.Item style={{ marginBottom: 0 }}>
              <Button
                type="primary"
                htmlType="submit"
                loading={loading}
                block
                style={{
                  height: '48px',
                  fontSize: '16px',
                  fontWeight: 'bold',
                  borderRadius: '8px'
                }}
              >
                {loading ? '登录中...' : '登录'}
              </Button>
            </Form.Item>
          </Form>

        {/* 第三方登录 */}
        <div>
          <Button
            block
            onClick={() => {
              // 纯前端：直接跳 Gitee 授权（回调到前端路由）
              const authorizeUrl = `https://gitee.com/oauth/authorize?client_id=fb2428e600444232b42e6e440fa526a268a93e12daa6ab0bea2f938b47cdcfb6&redirect_uri=${encodeURIComponent(window.location.origin + '/auth/gitee/callback')}&response_type=code&scope=user_info%20emails`
              window.location.href = authorizeUrl
            }}
            style={{ height: '40px', borderRadius: '8px' }}
          >
            使用 Gitee 登录
          </Button>
        </div>
        </Space>
      </Card>
      
      {/* 滑块验证组件（第三方库）*/}
      {captchaVisible && (
        <div style={{ position: 'fixed', inset: 0, background: 'rgba(0,0,0,0.45)', display: 'flex', alignItems: 'center', justifyContent: 'center', zIndex: 1000 }}>
          <div style={{ background: '#fff', padding: 12, borderRadius: 8, boxShadow: '0 8px 24px rgba(0,0,0,0.2)' }}>
            <div style={{ display: 'flex', justifyContent: 'flex-end' }}>
              <button onClick={handleCaptchaCancel} style={{ border: 'none', background: 'transparent', cursor: 'pointer', fontSize: 16 }}>×</button>
            </div>
            <SliderCaptchaCanvas
              width={320}
              height={180}
              pieceSize={50}
              tolerance={8}
              onSuccess={handleCaptchaSuccess}
              onCancel={handleCaptchaCancel}
            />
          </div>
        </div>
      )}
    </div>
  )
}

export default LoginPage
